/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tds;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Vector;

/**
 *
 * @author hoopaloopa
 */
public class SearchMonitor extends Thread {
	
	private SearchQuery query;
	private String outLoc;
	private BufferedWriter out;
	private Vector<String> errors;
	final private PrintStream log = System.out;
	
	public SearchMonitor (SearchQuery q, String location) {
		query = q;
		outLoc = location;
		errors = new Vector<String>();
		
	}

	@Override
	public void run() {
		
		try {
			out = new BufferedWriter(new FileWriter(new File(outLoc)));
			Twitter twitter = new Twitter();

			for(int i = 0; ; ++i) {
				try {
					log.println("Iteration #" + i);
					SearchResult currentResult = twitter.search(this.query);
					writeTweets(currentResult.getTweets());
					this.query.refresh(currentResult);
					this.sleepSeconds(20);
				} catch (SearchRateLimitException e) {
					log.println(e.getMessage());
					this.sleepSeconds(10);
				} catch (Exception e) {
					log.println(e.getMessage());
					errors.add(e.getMessage());
				}
			}
		} catch (IOException e) {
			log.println(e.getMessage());
		}
	}
	
	public void sleepSeconds(int s) {
		try { this.sleep(1000 * s); }
		catch (InterruptedException e) {}
	}
	
	public void writeTweets(Collection<Tweet> c) throws IOException {
		for (Tweet t : c) {
			out.write(t.toString());
			out.newLine();
		}
		out.flush();
	}
	
}
